package com.test.mchelepesa.activity_fragment_rice.login_rice;

import static com.test.mchelepesa.constant_rice.Constant_rice.VerificationFlag_APPLY;
import static com.test.mchelepesa.constant_rice.Constant_rice.VerificationFlag_HOME;
import static com.test.mchelepesa.constant_rice.Constant_rice.VerificationFlag_PROCESS;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.IntentSenderRequest;
import androidx.activity.result.contract.ActivityResultContracts;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.auth.api.identity.GetPhoneNumberHintIntentRequest;
import com.google.android.gms.auth.api.identity.Identity;
import com.test.mchelepesa.R;
import com.test.mchelepesa.activity_fragment_rice.info_rice.BindAccountActivity_rice;
import com.test.mchelepesa.activity_fragment_rice.info_rice.FaceInfoActivity_rice;
import com.test.mchelepesa.activity_fragment_rice.info_rice.InfoUploadActivity_rice;
import com.test.mchelepesa.activity_fragment_rice.base_rice.BaseActivity_rice;
import com.test.mchelepesa.activity_fragment_rice.info_rice.OcrInfoActivity_rice;
import com.test.mchelepesa.activity_fragment_rice.loan_rice.LoanApplyActivity_rice;
import com.test.mchelepesa.activity_fragment_rice.loan_rice.LoanMainActivity_rice;
import com.test.mchelepesa.bean_rice.StaticConfig_rice;
import com.test.mchelepesa.bean_rice.process_rice.ProcessInfo_rice;
import com.test.mchelepesa.dialog_rice.CustomerServiceDialog_rice;
import com.test.mchelepesa.util_rice.StringUtil_rice;
import com.test.mchelepesa.util_rice.helper_rice.UserInfoHelper_rice;
import com.test.mchelepesa.util_rice.http_rice.HttpManager_rice;
import com.test.mchelepesa.view_rice.RiceEditText;

public class VerificationActivity extends BaseActivity_rice {

    public static Runnable afterVerificationRunnable = null;

    private TextView prefixTv;
    private RiceEditText mobileEt;
    private View editBtn,confirmBtn;
    private View mobileLine;
    private TextView otpChannelTitleTv;
    private TextView otpChannelTv;
    private ImageView otpChannelIv;
    private View otpChannelLineView;
    private View channelSelectView;
    private EditText otpEt;
    private TextView sendCodeTv;
    private View otpInputLine;

    private final String Type_SMS = "SMS";
    private final String Type_Whatsapp = "WHATSAPP";

    private String selectedType = Type_SMS;

    private String confirmMobile;
    private String confirmType;

    private final View.OnClickListener getCodeClick = v -> {

        prefixTv.setVisibility(View.VISIBLE);
        mobileLine.setVisibility(View.GONE);

        channelSelectView.setVisibility(View.GONE);
        otpChannelLineView.setBackgroundColor(Color.parseColor("#FFF8F8F8"));
        otpChannelIv.setBackgroundResource(R.drawable.icon_item_bottom);

        mobileEt.setEnabled(false);
        editBtn.setVisibility(View.VISIBLE);
        confirmBtn.setVisibility(View.GONE);
        mobileEt.clearFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) imm.hideSoftInputFromWindow(mobileEt.getWindowToken(), 0);
        mobileEt.setFocusableInTouchMode(false);

        String mobile = mobileEt.getTextString();

        if (TextUtils.isEmpty(mobile)){
            Toast.makeText(this,getString(R.string.tips_enter_phone_num),Toast.LENGTH_SHORT).show();
            return;
        }

        HttpManager_rice.getInstance().saveUserBuriedPoint("VERIFICATION_GET_CODE_CLICK");

        HttpManager_rice.getInstance().sendWhatsAppCode(mobile,selectedType);

    };

    private boolean phoneNumberHintFlag = true;

    private final ActivityResultLauncher<IntentSenderRequest> phoneNumberHintLauncher = registerForActivityResult(
            new ActivityResultContracts.StartIntentSenderForResult(),
            result -> {
                try {

                    String mobile = Identity.getSignInClient(this).getPhoneNumberFromIntent(result.getData());

                    if (TextUtils.isEmpty(mobile)) return;

                    String areaCodeText = StaticConfig_rice.getMobilePrefix();

                    if (mobile.startsWith(areaCodeText)) mobileEt.setText(mobile.replace(areaCodeText,""));
                    else mobileEt.setText(mobile);

                } catch (Exception e) {
                    StringUtil_rice.printException(e);
                }
            }
    );

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verification);

        findViewById(R.id.activity_ver_ib_cs).setOnClickListener(v -> {
            HttpManager_rice.getInstance().saveUserBuriedPoint("VERIFICATION_CUSTOMER_SERVICE_CLICK");
            new CustomerServiceDialog_rice(this).show();
        });

        prefixTv = findViewById(R.id.activity_ver_tv_prefix);
        mobileEt = findViewById(R.id.activity_ver_et_mobile);
        editBtn = findViewById(R.id.activity_ver_ib_edit);
        confirmBtn = findViewById(R.id.activity_ver_btn_confirm);
        mobileLine = findViewById(R.id.activity_ver_line_mobile);
        otpChannelTitleTv = findViewById(R.id.activity_ver_tv_otp_channel_title);
        View otpChannelView = findViewById(R.id.activity_ver_view_otp_channel);
        otpChannelTv = findViewById(R.id.activity_ver_tv_otp_channel);
        otpChannelIv = findViewById(R.id.activity_ver_iv_otp_channel);
        otpChannelLineView = findViewById(R.id.activity_ver_line_otp_channel);
        channelSelectView = findViewById(R.id.activity_ver_view_channel_select);
        TextView smsTv = findViewById(R.id.activity_ver_tv_channel_sms);
        TextView whatsappTv = findViewById(R.id.activity_ver_tv_channel_whatsapp);
        otpEt = findViewById(R.id.activity_ver_et_otp);
        sendCodeTv = findViewById(R.id.activity_ver_btn_send_code);
        Button continueBtn = findViewById(R.id.activity_ver_btn_continue);
        otpInputLine = findViewById(R.id.activity_ver_line_otp_input);

        prefixTv.setText(StaticConfig_rice.getMobilePrefix());

        mobileEt.setBpType("VERIFICATION_PHONE_NUMBER_INPUT");

        if (ProcessInfo_rice.getInstance().isNeedVerWhatsApp()){

            whatsappTv.setOnClickListener(v -> {
                if (Type_Whatsapp.equalsIgnoreCase(selectedType)) return;
                HttpManager_rice.getInstance().saveUserBuriedPoint("VERIFICATION_WHATSAPP_CLICK");
                selectWhatsapp();
            });

            if (!ProcessInfo_rice.getInstance().isNeedVerSms()) selectWhatsapp();

        }else whatsappTv.setVisibility(View.GONE);

        otpChannelView.setOnClickListener(v -> {
            if (channelSelectView.getVisibility()==View.VISIBLE){
                channelSelectView.setVisibility(View.GONE);
                otpChannelLineView.setBackgroundColor(Color.parseColor("#FFF8F8F8"));
                otpChannelIv.setBackgroundResource(R.drawable.icon_item_bottom);
            }else {
                channelSelectView.setVisibility(View.VISIBLE);
                otpChannelLineView.setBackgroundColor(getColor(R.color.orange_rice));
                otpChannelIv.setBackgroundResource(R.drawable.icon_item_top);
            }
        });

        if (ProcessInfo_rice.getInstance().isNeedVerSms()){

            smsTv.setOnClickListener(v -> {
                if (Type_SMS.equalsIgnoreCase(selectedType)) return;
                HttpManager_rice.getInstance().saveUserBuriedPoint("VERIFICATION_SMS_CLICK");
                selectSms();
            });

            selectSms();

        }else smsTv.setVisibility(View.GONE);

        confirmType = selectedType;

        confirmMobile = UserInfoHelper_rice.getInstance().getMobil_rice();
        mobileEt.setText(confirmMobile);

        mobileEt.addOnFocusChangeListener((v, hasFocus) -> {

            if (hasFocus && phoneNumberHintFlag){

                phoneNumberHintFlag = false;

                GetPhoneNumberHintIntentRequest request = GetPhoneNumberHintIntentRequest.builder().build();

                Identity.getSignInClient(this).getPhoneNumberHintIntent(request)
                        .addOnSuccessListener(result -> {
                            try {
                                phoneNumberHintLauncher.launch(new IntentSenderRequest.Builder(result.getIntentSender()).build());
                            } catch (Exception e) {
                                StringUtil_rice.printException(e);
                            }
                        })
                        .addOnFailureListener(e -> Log.e("=Login", "Phone number hint failed"));

            }

        });

        if (ProcessInfo_rice.getInstance().mobileCanEdit()){

            editBtn.setVisibility(View.VISIBLE);

            editBtn.setOnClickListener(v -> {

                prefixTv.setVisibility(View.GONE);
                mobileLine.setVisibility(View.VISIBLE);

                mobileEt.setEnabled(true);
                HttpManager_rice.getInstance().saveUserBuriedPoint("VERIFICATION_EDIT_MOBILE_CLICK");
                editBtn.setVisibility(View.GONE);
                confirmBtn.setVisibility(View.VISIBLE);
                mobileEt.setFocusableInTouchMode(true);
                mobileEt.requestFocus();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) imm.showSoftInput(mobileEt, InputMethodManager.SHOW_IMPLICIT);
                mobileEt.setSelection(mobileEt.getTextString().length());
            });

            confirmBtn.setOnClickListener(v -> {

                prefixTv.setVisibility(View.VISIBLE);
                mobileLine.setVisibility(View.GONE);

                mobileEt.setEnabled(false);
                HttpManager_rice.getInstance().saveUserBuriedPoint("VERIFICATION_CONFIRM_MOBILE_CLICK");
                editBtn.setVisibility(View.VISIBLE);
                confirmBtn.setVisibility(View.GONE);
                mobileEt.clearFocus();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) imm.hideSoftInputFromWindow(mobileEt.getWindowToken(), 0);
                mobileEt.setFocusableInTouchMode(false);
            });

        }else editBtn.setVisibility(View.GONE);

        otpEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {
                String mobile = mobileEt.getTextString();
                String code = otpEt.getText().toString();
                if (TextUtils.isEmpty(mobile)) return;
                if (TextUtils.isEmpty(code) || s.length()<4) return;
                HttpManager_rice.getInstance().saveUserBuriedPointAndUpload("VERIFICATION_CONFIRM_MOBILE_CLICK");
                HttpManager_rice.getInstance().checkWhatsAppCode(confirmMobile,confirmType,code);
            }
        });

        otpEt.setOnFocusChangeListener((v, hasFocus) -> {
            otpInputLine.setBackgroundColor(hasFocus ? getColor(R.color.orange_rice) : Color.parseColor("#FFF8F8F8"));
        });

        sendCodeTv.setOnClickListener(getCodeClick);

        //Next
        continueBtn.setOnClickListener(v -> {

            String mobile = mobileEt.getTextString();
            String code = otpEt.getText().toString();

            if (TextUtils.isEmpty(mobile)){
                Toast.makeText(this,getString(R.string.tips_enter_phone_num),Toast.LENGTH_SHORT).show();
                return;
            }

            if (TextUtils.isEmpty(code)){
                Toast.makeText(this,getString(R.string.tips_enter_otp_code),Toast.LENGTH_SHORT).show();
                return;
            }

            HttpManager_rice.getInstance().saveUserBuriedPointAndUpload("VERIFICATION_NEXT_CLICK");

            HttpManager_rice.getInstance().checkWhatsAppCode(confirmMobile,confirmType,code);

        });

    }

    private void selectSms(){

        selectedType = Type_SMS;

        channelSelectView.setVisibility(View.GONE);
        otpChannelTitleTv.setText(getString(R.string.verification_channel_title,getString(R.string.sms)));
        otpChannelTv.setText(getString(R.string.sms));

        channelSelectView.setVisibility(View.GONE);
        otpChannelLineView.setBackgroundColor(Color.parseColor("#FFF8F8F8"));
        otpChannelIv.setBackgroundResource(R.drawable.icon_item_bottom);
    }

    private void selectWhatsapp(){

        selectedType = Type_Whatsapp;

        channelSelectView.setVisibility(View.GONE);
        otpChannelTitleTv.setText(getString(R.string.verification_channel_title,getString(R.string.whatsapp)));
        otpChannelTv.setText(getString(R.string.whatsapp));

        channelSelectView.setVisibility(View.GONE);
        otpChannelLineView.setBackgroundColor(Color.parseColor("#FFF8F8F8"));
        otpChannelIv.setBackgroundResource(R.drawable.icon_item_bottom);
    }

    @SuppressLint("SetTextI18n")
    public void onGetCodeSuccessful(){

        runOnUiThread(() -> {
            confirmMobile = StringUtil_rice.getSafeString(mobileEt.getTextString());
            confirmType = selectedType;
            sendCodeTv.setAlpha(0.4f);
            sendCodeTv.setOnClickListener(null);
        });

        new Thread(() -> {
            int count = 60;
            while (count-->0){
                final int fc = count;
                if (!isClose()){
                    runOnUiThread(() -> sendCodeTv.setText(fc+"s"));
                }
                try {
                    Thread.sleep(999);
                } catch (InterruptedException e) {
                    StringUtil_rice.printException(e);
                }
            }

            if (!isClose()){
                runOnUiThread(() -> {
                    sendCodeTv.setAlpha(1f);
                    sendCodeTv.setText(getString(R.string.send));
                    sendCodeTv.setOnClickListener(getCodeClick);
                });
            }

        }).start();

    }

    public void onCheckSuccessful(){
        UserInfoHelper_rice.getInstance().setMobile_rice(confirmMobile);
        HttpManager_rice.getInstance().requestUserProcess();
    }

    @Override
    public void onUserProcessResponse_rice() {
        runOnUiThread(() -> {
            if (ProcessInfo_rice.getInstance().isNeedVerification())
                Toast.makeText(this,getString(R.string.mobile_verification_failed_tips),Toast.LENGTH_SHORT).show();
            else {

                switch (UserInfoHelper_rice.getInstance().getVerificationFlag()){
                    case VerificationFlag_HOME:
                        startActivityForSingleTop_rice(LoanMainActivity_rice.class);
                        break;
                    case VerificationFlag_APPLY:

                        break;

                    case VerificationFlag_PROCESS:
                        String currentStepName = ProcessInfo_rice.getInstance().getCurrentStepName();
                        if (TextUtils.isEmpty(currentStepName))//流程上报完毕
                            startActivity_rice(LoanApplyActivity_rice.class);
                        else {
                            switch (currentStepName){
                                case "ocr_info":
                                    startActivity_rice(OcrInfoActivity_rice.class);
                                    break;
                                case "sefie_info":
                                    startActivity_rice(FaceInfoActivity_rice.class);
                                    break;
                                case "account_info":
                                    if (StaticConfig_rice.isSpecialBindAccount()){
                                        startActivity_rice(BindAccountActivity_rice.class);
                                        break;
                                    }
                                default:
                                    startActivity_rice(InfoUploadActivity_rice.class);
                            }
                        }
                        finish();
                        break;
                }

            }
        });
    }


    @Override
    public void onBackPressed() {}

    protected void onStop() {
        super.onStop();
        if (mobileEt!=null) mobileEt.clearFocus();
        if (otpEt!=null) otpEt.clearFocus();
    }

}